package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.domain.Product;
import cn.wolfcode.shop.domain.Property;
import cn.wolfcode.shop.domain.PropertyValue;
import cn.wolfcode.shop.mapper.PropertyMapper;
import cn.wolfcode.shop.mapper.PropertyValueMapper;
import cn.wolfcode.shop.service.IPropertyService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class PropertyServiceImpl implements IPropertyService {
    @Autowired
    private PropertyMapper propertyMapper;
    @Autowired
    private PropertyValueMapper propertyValueMapper;

    @Override
    public List<Property> listByCatalogId(Long catalogId) {
        List<Property> properties=propertyMapper.selecyByCatalogId(catalogId);
        return properties;
    }

    @Override
    public void saveOrUpdate(Property property) {
        if(property.getId()==null){//新增
            propertyMapper.insert(property);
        }else{//编辑
            Property pt = propertyMapper.selectByPrimaryKey(property.getId());
            pt.setCatalogId(property.getCatalogId());
            pt.setName(property.getName());
            pt.setSort(property.getSort());
            pt.setType(property.getType());
            propertyMapper.updateByPrimaryKey(property);
        }
    }

    @Override
    public void deleteById(Long id) {
        propertyMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer selectForCountByCatalogId(Long catalogId) {
        Integer count = propertyMapper.selectForCountByCatalogId(catalogId);
        return count;
    }

    @Override
    public List<Property> listPropertysWithValues(Long catalogId) {
        List<Property> properties=propertyMapper.selecyByCatalogId(catalogId);
        properties.forEach(property -> {
            if(property.getType()==Property.PROPERTY_TYPE_SELECT) {
                List<PropertyValue> propertyValues = propertyValueMapper.selectByPropertyId(property.getId());
                property.setPropertyValueList(propertyValues);
            }
        });
        return properties;
    }

}
